<template>
	<view class="content">
		<uni-card>
			<view class="equips"><text class="texts">设备ID：</text>
				<input v-model="equipDetail.code" class="inputs" :maxlength="20" placeholder="输入设备ID/扫码获取"
					@input="codeInput($event)" @blur="codeBlur($event)" />

				<uni-icons type="closeempty" class="closeempty" color="#999999" v-if="equipDetail.code" @click="clearIcon" size="24"></uni-icons>

				<button class="search_btn" type="default" size="mini" @click="searchCode">查询</button>
			</view>
			<view class="equips"><text class="texts">主控版本：</text>{{equipDetail.masterVersion || ''}}</view>
			<view class="equips"><text class="texts">仓控版本：</text>{{equipDetail.binVersion || ''}}</view>
			<view class="equips"><text class="texts">是否在线：</text>
				<text class="isonline" v-if="equipDetail.isOnline==1">在线</text>
				<text class="offline" v-if="equipDetail.isOnline==0">离线</text>
			</view>
			<view class="equips"><text class="texts">最近告警：</text>{{equipDetail.alarmSemaphoreName || ''}}<text
					v-if="equipDetail.occurrenceTime">（{{equipDetail.occurrenceTime}}）</text></view>
			<view class="equips"><text class="texts">最近上线：</text>{{equipDetail.lastOnlineTime || ''}}</view>
			<view class="equips"><text class="texts">最近离线：</text>{{equipDetail.lastOfflineTime || ''}}</view>
			<view class="equips"><text class="texts">备注：</text>{{equipDetail.remark || ''}}
				<uni-icons v-if="equipDetail.id" type="compose" size="20" @click="isEditRemark"></uni-icons>
			</view>
			<view class="operate_btns">
				<button size="mini" @click="isOperate(1)">升级</button>
				<button size="mini" @click="isOperate(2)">查询版本</button>
				<!-- <button size="mini" @click="isOperate(3)">切换平台参数</button> -->
				<button size="mini" @click="isOperate(7)">切换平台参数</button>
				<!-- codeType !='DPCG' || codeType!='KPDG' -->
				<!-- <button size="mini" v-if="codeType == 'DPCG'" @click="isOperate(4,'升级主控制到(V006)')">升级主控制到(V006)</button>
				<button size="mini" v-if="codeType == 'KPDG'" @click="isOperate(5,'升级主控制到(V106)')">升级主控制到(V106)</button>
				<button size="mini" @click="isOperate(6,'升级仓控到(V108)')">升级仓控到(V108)</button> -->
			</view>
		</uni-card>
		<uni-card v-if="code">
			<p class="result">获取到的设备ID：{{code}}</p>
			<p class="result" v-if="Object.keys(searchMessage).length>0">
				查询版本通讯结果：{{searchMessage.message}}
			</p>
			<p class="result" v-if="Object.keys(updateMessage).length>0">
				{{updateMessage.updateType}}通讯结果：{{updateMessage.message}}<text
					v-if="updateMessage.code==200">,请耐心等待{{updateMessage.updateType}}大约2分钟</text>
			</p>
			<p class="result" v-if="Object.keys(binMessage).length>0">
				{{binMessage.updateType}}通讯结果：{{binMessage.message}}<text
					v-if="binMessage.code==200">,请耐心等待{{binMessage.updateType}}大约2分钟</text>
			</p>
			<p class="result" v-if="Object.keys(platformMessage).length>0">
				切换平台参数通讯结果：{{platformMessage.message}}
			</p>
		</uni-card>

		<view class="scans">
			<image class="img" src="/static/image/scan-code.png" @click="onScanTap"></image>
		</view>

		<uni-popup ref="updatePopup" type="bottom" :animation="false">
			<view class="alertbox">
				<view class="alert_title">升级</view>
				<view class="boxone">
					<text class="labels">设备ID：</text>
					<text class="data-checkbox">{{equipDetail.code || ''}}</text>
				</view>
				<view class="boxone">
					<text class="labels">升级类型：</text>
					<uni-data-checkbox class="data-checkbox" mode="tag" :map="{text:'label',value:'code'}"
						v-model="updateForm.type" :localdata="enums.SOFTWARE_UPGRADE_TYPE" @change="updateTypeChange">
					</uni-data-checkbox>
				</view>
				<view class="boxone">
					<text class="labels">选择软件版本：</text>
					<uni-data-checkbox v-if="allowVersion.length>0" class="data-checkbox" mode="tag"
						:map="{text:'filename',value:'id'}" v-model="updateForm.softwareVersionId"
						:localdata="allowVersion">
					</uni-data-checkbox>
					<text v-if="updateForm.type&&allowVersion.length==0">暂无</text>
				</view>
				<view class="operate_btns">
					<button type="default" size="mini" class="cancle_btn" @click="closeUpdatePop">取消</button>
					<button type="primary" size="mini" class="confirm_btn" @click="isUpdate">确认</button>
				</view>
			</view>
		</uni-popup>

		<uni-popup ref="platformPopup" type="bottom" :animation="false">
			<view class="alertbox">
				<view class="alert_title">切换平台参数</view>
				<view class="boxone">
					<text class="labels">类型：</text>
					<!-- <uni-data-checkbox class="data-checkbox" mode="tag" :map="{text:'label',value:'code'}"
						v-model="platForm.type" :localdata="platFormType">
					</uni-data-checkbox> -->
					<uni-tag :text="platFormType.label" type="primary" />
				</view>
				<view class="boxone">
					<text class="labels">服务器地址：</text>
					<input v-model="platForm.url" class="data-checkbox" placeholder="请输入服务器地址" />
				</view>
				<view class="boxone">
					<text class="labels">端口号：</text>
					<input v-model="platForm.port" class="data-checkbox" placeholder="请输入端口号" />
				</view>
				<view class="boxone">
					<text class="labels">用户名：</text>
					<input v-model="platForm.username" class="data-checkbox" placeholder="请输入用户名" />
				</view>
				<view class="boxone">
					<text class="labels">密码：</text>
					<input v-model="platForm.password" class="data-checkbox" password type="text" placeholder="请输入密码" />
				</view>
				<view class="operate_btns">
					<button type="default" size="mini" class="cancle_btn" @click="closePlatformPop">取消</button>
					<button type="primary" size="mini" class="confirm_btn" @click="isPlatForm">确认</button>
				</view>
			</view>
		</uni-popup>
		<!-- 修改备注 -->
		<uni-popup ref="remarkPopup" type="center" :animation="false">
			<view class="alertbox remarkbox">
				<view class="alert_title">编辑备注信息</view>
				<view class="boxone remark-cont">
					<textarea style="width:100%;" v-model="remarkForm.remark" class="data-checkbox" :confirm-type="next"
						placeholder="请输入备注" />
				</view>
				<view class="operate_btns">
					<button type="default" size="mini" class="cancle_btn" @click="closeRemarkPop">取 消</button>
					<button type="primary" size="mini" class="confirm_btn" @click="isRemark">确 认</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		mapState,
	} from 'vuex';
	import {
		equipment,
		software,
		softwareupgrade,equipmentupgrade
	} from "@/api/api.js";
	export default {
		data() {
			return {
				code: "", //设备code
				equipDetail: {}, //设备详情信息
				softVersionOption: [], //软件版本option
				updateForm: {
					type: "",
					softwareVersionId: ""
				}, //升级form
				platForm: {
					type: 1,
					password: "",
					port: "",
					url: "",
					username: "",
				},
				searchMessage: {},
				updateMessage: {},
				binMessage: {},
				platformMessage: {},
				codeType: '',
				allowVersion: [], //升级类型对应的软件版本list
				platFormType: {
					"code": 1,
					"label": "主平台"
				},

				remarkForm: {
					remark: "",
					id: ""
				}
			}
		},
		computed: {
			...mapState(['enums'])
		},
		onLoad() {
			this.$store.dispatch("enumsAll");
			this.getSoftVersion();
		},
		methods: {
			codeInput(e) {
				let val = e.detail.value;
				let inputRule = /[\W]/g //限制数字和字母
				this.$nextTick(() => {
					this.equipDetail.code = val.replace(inputRule, '');
					let code2 = val.substr(4, 4);
					this.codeType = code2;
					this.code = this.equipDetail.code;
				})
			},
			codeBlur(e) {
				// let val = e.detail.value;
				// if (val) {
				// 	let code2 = val.substr(4, 4);
				// 	this.codeType = code2;
					
				// 	this.code = val;
				// 	this.equipDetail = {};
				// 	this.equipDetail.code = val;
				// }
			},
			// 扫码
			onScanTap() {
				let token = uni.getStorageSync('token') || null;
				if (!token) {
					uni.reLaunch({
						url: '/pages/login/index'
					})
					return;
				}
				this.code = "";
				this.codeType = "";
				this.resetData();
				uni.scanCode({
					onlyFromCamera: true,
					scanType: 'qrCode',
					success: (res) => {
						// 去除字符串中空格 回车换行
						let str = res.result.trim().replace(/\s*/g,"").replace(/[\r\n]/g,"");
						// let index = str.lastIndexOf('/');
						// 截取二维码后20位
						let code = str.substr(-20, 20);
						this.code = code;
						let code2 = code.substr(4, 4);
						this.codeType = code2;
						this.getEquipDetail();
					},
					fail: (err) => {}
				});
			},
			resetData() {
				this.equipDetail = {};
				this.updateForm = {
					type: "",
					softwareVersionId: ""
				};
				this.platForm = {
					type: 1,
					password: "",
					port: "",
					url: "",
					username: "",
				};

				this.searchMessage = {};
				this.updateMessage = {};
				this.binMessage = {};
				this.platformMessage = {};
			},
			// 获取充电柜设备信息
			async getEquipDetail() {
				if (this.code.length != 20) {
					this.$Toast.none('请输入20位正确的设备ID！');
					this.code = "";
					return;
				}
				let code1 = this.code.substr(0, 4);
				let code2 = this.code.substr(4, 4);
				let code3 = this.code.substr(8, this.code.length - 8);
				let regPos = / ^\d+$/;
				let reg = /^[\d]+$/;

				if (this.code.length != 20 || code1 != 'CC08' || (code2 != 'DPCG' && code2 != 'KPDG' && code2 != 'WSNY') || !reg
					.test(code3)) {
					this.code = "";
					this.resetData();
					this.$Toast.none('设备ID格式错误,请重新扫码或输入');
					return;
				}

				let datas = await equipment('/list', 'post', {
					code: this.code,
					equipmentType: "CHARGING_CABINET",
					pageNum: 1,
					pageSize: 10
				});
				if (datas.code == 200 && datas.data.length > 0) {
					this.equipDetail = datas.data[0];
				} else {
					this.equipDetail = {};
					this.code = "";
					this.$Toast.none('未查到该设备信息！');
				}
			},
			searchCode() {
				let token = uni.getStorageSync('token') || null;
				if (!token) {
					uni.reLaunch({
						url: '/pages/login/index'
					})
					return;
				}
				if (!this.code) {
					this.$Toast.none('请输入设备ID或扫描设备二维码获取');
					return;
				}
				this.resetData();
				this.getEquipDetail();
			},
			closeUpdatePop() {
				this.$refs.updatePopup.close();
			},
			closePlatformPop() {
				this.$refs.platformPopup.close();
			},
			isOperate(type, msg) {
				let that = this;
				let token = uni.getStorageSync('token') || null;
				if (!token) {
					uni.reLaunch({
						url: '/pages/login/index'
					})
					return;
				}
				if (Object.keys(this.equipDetail).length == 0) {
					this.$Toast.none('请先扫描设备二维码~');
					return;
				}
				if (this.equipDetail.isOnline != 1) {
					this.$Toast.none('请确认设备是否在线');
					return;
				}
				switch (type) {
					case 1:
						this.allowVersion = [];
						this.updateForm = {
							type: "",
							softwareVersionId: ""
						};
						this.$refs.updatePopup.open();
						break;
					case 2:
						uni.showModal({
							title: '提示',
							content: '确认要查询吗?',
							success(res) {
								if (res.confirm) {
									that.doSearch();
								}
							}
						})
						break;
					case 3:
						this.$refs.platformPopup.open();
						this.platForm = {
							type: 1,
							password: "",
							port: "",
							url: "",
							username: "",
						};
						break;
					case 4:
						uni.showModal({
							title: '提示',
							content: `确认要${msg}吗?`,
							success(res) {
								if (res.confirm) {
									that.masterUpdate(type, msg);
								}
							}
						})
						break;
					case 5:
						uni.showModal({
							title: '提示',
							content: `确认要${msg}吗?`,
							success(res) {
								if (res.confirm) {
									that.masterUpdate(type, msg);
								}
							}
						})
						break;
					case 6:
						uni.showModal({
							title: '提示',
							content: `确认要${msg}吗?`,
							success(res) {
								if (res.confirm) {
									that.masterUpdate(type, msg);
								}
							}
						})
						break;
					case 7:
						uni.showModal({
							title: '提示',
							content: `确认要切换平台参数吗?`,
							success(res) {
								if (res.confirm) {
									that.solidPlatForm();
								}
							}
						})
						break;
				}
			},
			// 固化平台参数
			solidPlatForm() {
				this.$Toast.loading('操作中~');
				let datas = {
					type: 1,
					password: "DPCGJT8!&X35",
					port: "8883",
					url: "ssl://cd-mqtt.chinatowercom.cn",
					username: "DPCG",
				};
				let params = Object.assign({
					equipmentCode: this.equipDetail.code,
					param: datas,
				});
				equipment('/control/serverparam', 'post', params).then(res => {
					this.platformMessage = res;
					if (res.code == 200) {
						this.$Toast.none('切换平台参数成功');
					}
				}).catch(err => {
					this.platformMessage = err;
				});
			},
			// 固化升级
			masterUpdate(type, msg) {
				this.$Toast.loading('升级中~');
				let params = {
					equipmentCode: this.equipDetail.code,
					type: "",
					softwareVersionId: ""
				};
				if (type == 4) {
					params.type = 'MASTER';
					params.softwareVersionId = '1571754969366503426';
				}
				if (type == 5) {
					params.type = 'MASTER';
					params.softwareVersionId = '1592419020375310337';
				}
				if (type == 6) {
					params.type = 'BIN';
					params.softwareVersionId = '1571746146434129921';
				}
				params.equipmentCode = this.equipDetail.code;
				softwareupgrade(
					`/insert?equipmentCode=${params.equipmentCode}&type=${params.type}&softwareVersionId=${params.softwareVersionId}`,
					'post').then(res => {
					if (type == 4 || type == 5) {
						this.updateMessage = res;
						this.updateMessage.updateType = msg;
					} else if (type == 6) {
						this.binMessage = res;
						this.binMessage.updateType = msg;
					}
					if (res.code == 200) {
						this.$Toast.none('升级成功！');
					}
				}).catch(err => {
					if (type == 4 || type == 5) {
						this.updateMessage = err;
						this.updateMessage.updateType = msg;
					} else if (type == 6) {
						this.binMessage = err;
						this.binMessage.updateType = msg;
					}
				});
			},
			// 获取软件版本option
			async getSoftVersion() {
				let datas = await software(`/enables?equipmentType=CHARGING_CABINET`, 'get');
				this.softVersionOption = datas.data;
			},
			// 升级
			isUpdate() {
				if (!this.updateForm.type) {
					this.$Toast.none('请选择升级类型');
					return;
				}
				if (this.allowVersion.length == 0) {
					this.$Toast.none('暂无软件版本');
					return;
				}
				if (!this.updateForm.softwareVersionId) {
					this.$Toast.none('请选择软件版本');
					return;
				}
				let that = this;
				uni.showModal({
					title: '提示',
					content: '确认要升级吗？',
					success(res) {
						if (res.confirm) {
							that.confirmUpdate();
						}
					}
				})
			},
			confirmUpdate() {
				this.$Toast.loading('升级中~');
				let params = {
					...this.updateForm
				};
				params.equipmentCode = this.equipDetail.code;
				this.updateMessage = {};
				equipmentupgrade(
					`/insert?equipmentCode=${params.equipmentCode}&type=${params.type}&softwareVersionId=${params.softwareVersionId}`,
					'post', params).then(res => {
					this.updateMessage = res;
					this.filterUpdateType(params.type);
					if (res.code == 200) {
						this.$Toast.none('升级成功！');
						this.$refs.updatePopup.close();
					}
				}).catch(err => {
					this.updateMessage = err;
					this.filterUpdateType(params.type);
				})
			},
			filterUpdateType(type) {
				switch (type) {
					case 'MASTER':
						this.updateMessage.updateType = '主控升级';
						break;
					case 'BIN':
						this.updateMessage.updateType = '仓控升级';
						break;
					case 'CABINET':
						this.updateMessage.updateType = '柜控升级';
						break;
					case 'POWER_SUPPLY':
						this.updateMessage.updateType = '电源升级';
						break;
				}
			},
			// 查询
			doSearch() {
				this.$Toast.loading('查询中~');
				equipment('/param/read/version', 'get', {
					code: this.equipDetail.code
				}).then(res => {
					this.searchMessage = res;
					if (res.code == 200) {
						this.$Toast.none('查询成功');
						this.getEquipDetail();
					}
				}).catch(err => {
					this.searchMessage = err;
				});
			},
			isPlatForm() {
				// if (!this.platForm.type) {
				// 	this.$Toast.none('请选择类型');
				// 	return;
				// }
				if (!this.platForm.url) {
					this.$Toast.none('请输入服务器地址');
					return;
				}
				if (!this.platForm.port) {
					this.$Toast.none('请输入端口号');
					return;
				}
				if (!this.platForm.username) {
					this.$Toast.none('请输入用户名');
					return;
				}
				if (!this.platForm.password) {
					this.$Toast.none('请输入密码');
					return;
				}
				let that = this;
				uni.showModal({
					title: '提示',
					content: '确认要切换平台参数吗？',
					success(res) {
						if (res.confirm) {
							that.confirmPlatForm();
						}
					}
				})
			},
			confirmPlatForm() {
				this.$Toast.loading('操作中~');
				let params = Object.assign({
					equipmentCode: this.equipDetail.code,
					param: this.platForm,
				});
				equipment('/control/serverparam', 'post', params).then(res => {
					this.platformMessage = res;
					if (res.code == 200) {
						this.$Toast.none('切换平台参数成功');
						this.closePlatformPop();
					}
				}).catch(err => {
					this.platformMessage = err;
				});
			},
			updateTypeChange(e) {
				this.allowVersion = [];
				this.updateForm.softwareVersionId = "";
				let val = e.detail.value;
				switch (val) {
					case 'MASTER': //主控
						if (this.codeType == 'DPCG') {
							// this.allowVersion = this.softVersionOption.filter(item => item.filename.includes('_ZK') && item
							// 	.filename.includes('0_0_6'));
							this.allowVersion = this.softVersionOption.filter(item => item.filename.includes('_ZK_0'));
						} else if (this.codeType == 'KPDG') {
							this.allowVersion = this.softVersionOption.filter(item => item.filename.includes('_ZK_1'));
						}
						break;
					case 'BIN': //仓控
						this.allowVersion = this.softVersionOption.filter(item => item.filename.includes('_CK'));
						break;
					case 'CABINET': //柜控
						this.allowVersion = this.softVersionOption.filter(item => item.filename.includes('_GK'));
						break;
					case 'POWER_SUPPLY': //电源
						this.allowVersion = this.softVersionOption.filter(item => item.filename.includes('_DY'));
						break;
				}
				this.updateForm.softwareVersionId = this.allowVersion.length > 0 ? this.allowVersion[0].id : "";
			},
			// 修改备注
			isEditRemark() {
				this.$refs.remarkPopup.open();
				const {
					remark,
					id
				} = this.equipDetail;
				this.remarkForm = {
					remark,
					id
				};
			},
			closeRemarkPop() {
				this.$refs.remarkPopup.close();
				this.remarkForm = {
					remark: "",
					id: ""
				};
			},
			isRemark() {
				let that = this;
				uni.showModal({
					title: '提示',
					content: '确认要编辑备注信息吗？',
					success(res) {
						if (res.confirm) {
							that.confirmRemark();
						}
					}
				})
			},
			confirmRemark() {
				this.$Toast.loading('操作中~');
				equipment(`/update/remark?remark=${this.remarkForm.remark}&id=${this.remarkForm.id}`, 'put').then(res => {
					if (res.code == 200) {
						this.$Toast.none('备注编辑成功');
						this.closeRemarkPop();
						this.searchCode();
					}
				});
			},
			clearIcon() {
				this.code = "";
				this.resetData();
			},
		}
	}
</script>

<style scoped lang="scss">
	@import "@/static/css/common";

	.content {
		/deep/ .uni-card .uni-card__content {
			color: #000000;
			font-size: 30rpx;
			padding: 20rpx 0 !important;
		}

		/deep/ .uni-card {
			padding: 0 !important;
			margin: 15px 10px !important;
		}
		button {
			background: #1976D3;
			color: #ffffff;
			height: 66rpx;
			line-height: 66rpx;
		}
		.equips {
			@include flexLayout(center, flex-start);

			.texts {
				width: 160rpx;
				text-align: right;
			}

			.inputs {
				width: 57%;
				border-bottom: 2rpx solid #666666;
				padding-bottom: 10rpx;
			}

			margin: 10rpx;

			.isonline,
			.offline {
				border-radius: 10rpx;
				padding: 2rpx 10rpx;
				border: 2rpx solid #6A6A6A;
			}

			.isonline {
				border-color: #1976D3;
				color: #1976D3;
			}

			.offline {
				border-color: #f56c6c;
				color: #f56c6c;
			}

			.search_btn {
				height: 56rpx;
				line-height: 56rpx;
				position: absolute;
				right: 10rpx;
				padding: 0 10rpx;
			}
		}

		.scans {
			text-align: center;
			margin-top: 16%;

			.img {
				height: 100rpx;
				width: 100rpx;
			}
		}

		.operate_btns {
			text-align: center;
			margin: 50rpx 0 10rpx;

			button {
				margin-bottom: 10rpx;
			}

			button:not(:first-child) {
				margin-left: 30rpx;
			}

			.cancle_btn,
			.confirm_btn {
				height: 60rpx;
				line-height: 60rpx;
			}

			.cancle_btn {
				background: #f5f5f5;
				color: #000000;
			}
		}

		.alertbox {
			box-sizing: border-box;
			background-color: white;
			border-radius: 24rpx;
			width: 100%;
			height: auto;
			overflow-y: auto;
			padding: 20rpx;
			color: #333333;

			.alert_title {
				text-align: center;
				margin-bottom: 20rpx;
			}

			.address {
				margin-left: 50rpx;
			}

			.alert_btn {
				line-height: 66rpx;
				position: absolute;
				bottom: 30rpx;
				left: calc(50% - 110rpx);
				background-color: #51b7b9;
				width: 220rpx;
			}
		}

		.remarkbox {
			width: 560rpx;
		}

		.boxone {
			@include flexLayout(center, flex-start);
			border-bottom: 2rpx solid #dfdfdf;
			padding: 20rpx 0;

			.labels {
				display: inline-block;
				width: 250rpx;
				text-align: right;
			}

			.data-checkbox {
				width: 80%;
			}
		}

		.result {
			padding: 0 20rpx;
		}

		.remark-cont {
			margin: 20px 0;
			align-items: flex-start;
		}
	}
	.closeempty{
		position: relative;
		left: 8rpx;
		margin-right: 4rpx;
	}
</style>
